package org.evan.spring.validator.one;

import lombok.NonNull;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

public class PersonValidator implements Validator {

    @Override
    public boolean supports(@NonNull Class<?> clazz) {
        return Person.class.equals(clazz);
    }

    //校验规则
    @Override
    public void validate(@NonNull Object target, @NonNull Errors errors) {
        //判断name不能为空
        ValidationUtils.rejectIfEmpty(errors,"name","name.empty","name is null");
        //age 不能小于0，不能大于200
        Person person = (Person) target;
        if (person.getAge() < 0) {
            errors.rejectValue("age","age.value.invalid","age < 0");
        }else if(person.getAge() > 200){
            errors.rejectValue("age","age.value.invalid","age > 200");
        }
    }
}
